package com.qcu.intercept;

import com.qcu.exception.LoginRequestParamterFailException;
import com.qcu.util.JwtUtil;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import com.qcu.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Name: MyComputer
 * @ClassName LoginIntercept
 * @Description:
 * @date 2025/2/7 10:31
 */
@Component
@Slf4j
public class LoginIntercept implements HandlerInterceptor {

    @Resource
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {

//            String uri = request.getRequestURI();
//            log.info("拦截器拦截到请求：{}",uri);
//            if (uri.contains("/getEmailCode")){
//                return true;
//            }

            String authorization = request.getHeader("Authorization");
            String auth = (String) redisTemplate.opsForValue().get(authorization);
            if (auth == null){
                throw new LoginRequestParamterFailException();
            }
            Map<String, Object> token = JwtUtil.parseToken(authorization);
            ThreadLocalUtil.set(token);
            return true;
        }catch (LoginRequestParamterFailException e){
            // 向前端返回错误信息
            response.getWriter().write(Response.failure(ResponseCode.LOGIN_OUT).toString());
            response.setStatus(500);
            return false;
        } catch (Exception e) {
            response.setStatus(500);
            return false;
        }


//        ThreadLocalUtil.set(1);
//        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
